import {Component} from "@angular/core";
import {ArticleService} from "../../service/article/article.service";
import {ArticleReplyService} from "../../service/article/article.reply.service";
import {NavController, NavParams, PopoverController, ToastController} from "ionic-angular";
import {ScheduleFilterPage} from "./operator/operator";
import {Storage} from "@ionic/storage";
import {LoginPage} from "../login/login";
import {HistoryService} from "../../service/history/history.service";

@Component({
  selector: 'page-article',
  templateUrl: 'article.html',
  providers: [ArticleService, ArticleReplyService,HistoryService]
})

export class ArticlePage {
  private article: any;
  private replyContent?: string;

  constructor(private nav: NavController,
              private  navParams: NavParams,
              private  storage: Storage,
              private  historyService: HistoryService,
              private  toastCtrl: ToastController,
              private  articleService: ArticleService,
              private   articleReplyService: ArticleReplyService,
              private  popover: PopoverController) {
    this.article = this.navParams.get('article');
    this.articleService.findByCode(this.article.code).subscribe(res => {
      this.article = res.data;
      historyService.put(this.article);
    }, (err) => {
      console.log(err)
    });
  }


  replyClick() {
    if (!this.replyContent) {
      this.toastCtrl.create({
        message: '请输入回复内容！',
        duration: 2000
      }).present();
      return;
    }

    this.storage.get("oauthToken").then(value => {
      if (!value) {
        this.nav.push(LoginPage);
      } else {
        this.articleReplyService.save({
          content: this.replyContent,
          articleCode: this.article.code,
          token: value
        }).subscribe(() => {
          this.toastCtrl.create({
            message: "回复成功!",
            duration: 2000
          }).present();
        }, () => {
          this.toastCtrl.create({
            message: '回复失败！',
            duration: 2000
          }).present();
        });
      }
    });
  }

  articleOperator(myEvent: any) {
    this.popover.create(ScheduleFilterPage, {article: this.article}).present({
      ev: myEvent
    });
  }
}
